package com.itheima.service;

import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import com.itheima.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

public class UserService {
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();

    /**
     * 登录方法
     *
     * @param username
     * @param password
     * @return
     */

    public User login(String username, String password) {



        //获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //获取UserMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //调用方法
        User user = mapper.select(username, password);

        //释放资源
        sqlSession.close();

        return user;
    }

    /**
     * 注册功能
     */
    public boolean register(User user){
        //获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //获取UserMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //service调用方法
        User u = mapper.selectByUsername(user.getUsername());
        //判断用户是否存在
        if(u == null){
            //用户不存在，注册新用户
            mapper.add(user);
            sqlSession.commit();//提交事务
        }
        sqlSession.close();//关闭事务
        return u == null;
    }

    /**
     * 根据用户名查找查找用户
     * bymyself
     */
    public boolean selectUser(User user){
        //获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //获取UserMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        //调用service方法
        User u = mapper.selectByUsername(user.getUsername());
        //判断用户是否为null
        return u==null;
        //true就是无此用户    false就是已存在此用户
    }
}
